﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using ExcelDataReader;
using System.Data;
using LitJson;
using Client.Base;
using static Unity.VisualScripting.Icons;
using Newtonsoft.Json;
namespace Client.Editor
{
    public class Export_LanuageConfig : EditorWindow
    {
        private string excelPath = "";
        private bool existPath = true;
        private string[] excelFiles;
        private readonly int index_start = 1;
        private string gameSavePath => $"{Application.dataPath}/AssetsBundle/pk_game/config";
        private string baseSavePath => $"{Application.dataPath}/Resources";
        private bool isEncrypt = false;
        private bool IsEncrypt
        {
            get
            {
                if (!PlayerPrefs.HasKey("ConfigEncrypt_Lan"))
                {
                    PlayerPrefs.SetInt("ConfigEncrypt_Lan", 0);
                    PlayerPrefs.Save();
                }
                isEncrypt = PlayerPrefs.GetInt("ConfigEncrypt_Lan") == 1;
                return isEncrypt;
            }
            set
            {
                if (value != isEncrypt)
                {
                    isEncrypt = value;
                    int v = isEncrypt ? 1 : 0;
                    PlayerPrefs.SetInt("ConfigEncrypt_Lan", v);
                    PlayerPrefs.Save();
                }
            }
        }
        public static void ShowWindow()
        {
            // 创建并显示窗口
            Export_LanuageConfig window = GetWindow<Export_LanuageConfig>("导出多语言"); // 设置窗口的标题
            window.Show();
        }

        private void OnEnable()
        {
            //获取夫目录
            excelPath = Path.Combine(Path.GetDirectoryName(Application.dataPath), "Excel", "Language");
            if (!Directory.Exists(excelPath))
            {
                existPath = false;
            }
            else
            {
                excelFiles = Directory.GetFiles(excelPath, "*.xlsx"); // 只获取 .xlsx 文件
                if (excelFiles == null)
                {
                    Debug.LogError($"existPath not exist excel file.");
                }
            }
        }

        private void OnGUI()
        {
            if (!existPath)
            {
                //弹出一个不存在该目标的弹窗，点击确定关闭这个窗口
                // 弹出提示框，告诉用户目录不存在
                EditorUtility.DisplayDialog("目录不存在", $"{excelPath}", "确定");
                Close();
            }
            else
            {
                EditorGUILayout.BeginHorizontal("box");
                GUILayout.Label("路径: " + excelPath);
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.BeginHorizontal("box");
                //GUILayout.Label("是否加密:", GUILayout.Width(60));
                //IsEncrypt = EditorGUILayout.Toggle(IsEncrypt);
                EditorGUILayout.EndHorizontal();
                if (excelFiles != null)
                {
                    foreach (var file in excelFiles)
                    {
                        EditorGUILayout.BeginHorizontal("box");

                        if (GUILayout.Button(Path.GetFileName(file)))
                        {
                            ReadFile(file);
                            Debug.Log($"多语言导出完成:{Path.GetFileName(file)}");
                            AssetDatabase.Refresh();
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                    EditorGUILayout.BeginHorizontal("box");
                    GUI.color = Color.green; // 例如，将按钮颜色设置为绿色
                    if (GUILayout.Button("导出全部"))
                    {
                        foreach (var file in excelFiles)
                        {
                            ReadFile(file);
                            Debug.Log($"多语言导出完成:{Path.GetFileName(file)}");
                        }
                        AssetDatabase.Refresh();
                    }
                    GUI.color = Color.white;
                    EditorGUILayout.EndHorizontal();
                }
            }
        }
        private void ReadFile(string file)
        {
            using (var stream = File.Open(file, FileMode.Open, FileAccess.Read))
            {
                // 初始化 ExcelDataReader
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    // 将数据读入 DataTable
                    var result = reader.AsDataSet();
                    // 获取第一个工作表
                    DataTable table = result.Tables[0];
                    int languageCount = table.Rows[0].ItemArray.Length - 1;
                    ExcelInfo[] infos = new ExcelInfo[languageCount];
                    for (int i = 0; i < infos.Length; i++)
                    {
                        string name = table.Rows[0].ItemArray[i + 1].ToString();
                        infos[i] = new ExcelInfo(name);
                    }
                    for (int i = 0; i < infos.Length; i++)
                    {

                        for (int j = index_start; j < table.Rows.Count; j++)
                        {
                            CLanguage lang = new CLanguage
                            {
                                key = table.Rows[j][0].ToString(),
                                content = table.Rows[j][i + 1].ToString()
                            };
                            infos[i].ls.Add(lang);
                        }
                    }

                    for (int i = 0; i < infos.Length; i++)
                    {
                        string data = JsonConvert.SerializeObject(infos[i].ls);

                        if (IsEncrypt)
                        {
                            data = UniUtil.EncryptStringForAES(data);
                        }

                        string path = table.TableName.Trim().Equals("base") ? baseSavePath : gameSavePath;
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        string realPath = $"{path}/lan_{infos[i].name}.json";

                        File.WriteAllText(realPath, data, System.Text.Encoding.UTF8);
                    }
                }
            }
        }
        private class ExcelInfo
        {
            public string name { get; set; }
            public List<CLanguage> ls { get; set; }
            public ExcelInfo(string name)
            {
                this.name = name;
                ls = new List<CLanguage>();
            }
        }
    }
}

